<template>
  <ContainerContent :loading="loading" :pagination="pagination" @run="run">
    <template #header>
      <a-button type="primary" @click="siteState.visible = true">
        <i-icons-btn-add />
        添加站点
      </a-button>
      <a-button @click="open"> 分组管理 </a-button>
      <CloudFilterBar v-model="params" :run="run" :schemes="filterSchemes" />
    </template>
    <a-table
      ref="tableRef"
      v-model:selected-keys="selectedKeys"
      v-bind="commonTableProps"
      :columns="columns"
      :data="dealData"
      :row-selection="defaultRowSelection"
      @sorter-change="onSorterChange"
      @selection-change="onSelectChange">
      <template #region_info="{ record }">
        <edit-field
          type="select"
          edit-title="编辑区域"
          label="选择区域"
          mouse-over
          hover-table
          placeholder="请选择区域"
          rule-message="请选择区域"
          field="region_id"
          :required="false"
          :content="record.region_info.name"
          :options="areaListOptions"
          :fn="updateApiSiteApi"
          :refresh-fn="run"
          :params="{
            id: record.id
          }"
          :default-value="record.region_info.id">
        </edit-field>
      </template>
      <template #group_info="{ record }">
        <edit-field
          type="select"
          edit-title="变更分组"
          label="选择分组"
          mouse-over
          hover-table
          placeholder="请选择分组"
          rule-message="请选择分组"
          field="group_id"
          :content="record.group_info.name"
          :options="siteGroupOptions"
          :required="false"
          :fn="updateApiSiteApi"
          :refresh-fn="run"
          :params="{
            id: record.id
          }"
          :default-value="record.group_info.id">
        </edit-field>
      </template>
      <template #remark="{ record }">
        <edit-field
          type="input"
          edit-title="编辑备注"
          label="备注"
          mouse-over
          hover-table
          placeholder="请输入备注内容"
          field="remark"
          :no-verification="true"
          :max-length="20"
          :required="false"
          :content="record.remark"
          :fn="updateApiSiteApi"
          :refresh-fn="run"
          :params="{
            id: record.id
          }"
          :default-value="record.remark">
        </edit-field>
      </template>
      <template #resolve_info1="{ record }">
        {{ record.resolve_info.resolve_value || '-' }}
      </template>
      <template #resolve_info="{ record }">
        <section
          class="flex items-center gap-x-6px text-sm/22px resolve-status">
          <async-resolve-status
            v-model:status="record.resolve_info.resolve_status"
            v-model:loading="record.resolve_loading"
            @refresh="getResolveStatus(record)" />
        </section>
      </template>
      <template #https="{ record }">
        <span :class="{ 'text-#8F959E': !record.https }">
          {{ record.https ? '已开启' : '未开启' }}</span
        >
      </template>
      <template #status="{ record }">
        <a-switch
          :model-value="record.status"
          :checked-value="1"
          :unchecked-value="2"
          size="small"
          :before-change="
            (val) => handleBeforeChange(record, val as 1 | 2)
          "></a-switch>
      </template>
      <template #action="{ record }">
        <a-link
          :hoverable="false"
          @click="handleCommand('config', null, null, record)">
          配置
        </a-link>
        <a-link
          :hoverable="false"
          status="danger"
          @click="handleCommand('delete', null, run, record)">
          删除
        </a-link>
      </template>
    </a-table>
    <template #footer-prefix>
      <section class="flex-center gap-x-4">
        <a-button :disabled="!selectedKeys.length" @click="handleRegionChange">
          变更区域
        </a-button>
        <a-button :disabled="!selectedKeys.length" @click="handleGroupChange">
          变更分组
        </a-button>
        <a-button
          :disabled="!selectedKeys.length"
          @click="handleCommand('cache', selectedKeys, run)">
          清理缓存
        </a-button>
      </section>
    </template>
    <add-site-drawer
      v-model:visible="siteState.visible"
      v-model:loading="siteState.loading"
      :area-options="areaListOptions"
      :group-options="siteGroupOptions"
      @refresh="run" />
    <batch-edit-region-dialog
      v-model:visible="regionState.visible"
      :region-ids="regionState.ids"
      :area-options="areaListOptions"
      @refresh="run" />
    <batch-edit-group-dialog
      v-model:visible="groupState.visible"
      :group-ids="groupState.ids"
      :group-options="siteGroupOptions"
      @refresh="run" />
    <site-group-drawer v-model:visible="visible" @refresh="getSiteGroup" />
  </ContainerContent>
</template>
<script lang="ts" setup>
import type { SiteListItem } from '@/apis/model/site'
import {
  getApiSiteQueryApi,
  updateApiSiteApi,
  updateApiSiteResolveStatusApi
} from '@/apis/modules/site/site'
import ContainerContent from '@/components/ContentContainer.vue'
import type {
  CloudFilterBarScheme,
  CloudFilterBarState
} from '@/components/filter-bar/types'
import { useTable } from '@/hooks'
import { useListRequest } from '@/hooks/useListRequest'
import { commonTableProps, defaultRowSelection } from '@/utils/table'
import useCommand from '../actions'
import AddSiteDrawer from '../components/AddSiteDrawer.vue'
import AsyncResolveStatus from '../components/AsyncResolveStatus.vue'
import BatchEditGroupDialog from '../components/BatchEditGroupDialog.vue'
import BatchEditRegionDialog from '../components/BatchEditRegionDialog.vue'
import SiteGroupDrawer from '../components/SiteGroupDrawer.vue'
import useGroupArea from '../hooks/useGroupArea'
import useTableColumn from './column'
const siteState = reactive({
  visible: false,
  loading: false,
  record: {} as any
})

const { visible, open } = usePopup()
const regionState = reactive({
  visible: false,
  ids: [] as string[]
})
const groupState = reactive({
  visible: false,
  ids: [] as string[]
})
const { handleCommand } = useCommand()
const { areaListOptions, siteGroupOptions, getSiteGroup } = useGroupArea()
const params = ref<CloudFilterBarState>({
  order: 'desc',
  sort: 'created_at'
})
const handleRegionChange = () => {
  regionState.visible = true
  regionState.ids = selectedKeys.value as string[]
}
const handleGroupChange = () => {
  groupState.visible = true
  groupState.ids = selectedKeys.value as string[]
}

const dealData = ref<SiteListItem[]>([])
const { data, loading, run, pagination } = useListRequest(getApiSiteQueryApi, {
  immediate: true,
  params,
  afterFn: (res) => {
    dealData.value = (res?.list || []).map((item: any) => {
      item.resolve_loading = false
      return item
    })
  }
})
const filterSchemes = computed<CloudFilterBarScheme>(() => {
  const widget = {
    widgets: [
      {
        widget: 'select',
        field: 'region_id',
        allText: '全部区域',
        options: areaListOptions.value
      },
      {
        widget: 'select',
        field: 'group_id',
        allText: '全部分组',
        options: siteGroupOptions.value
      },
      {
        widget: 'strong-search',
        placeholder: '默认按照站点搜索',
        options: [
          {
            label: '站点',
            field: 'domain'
          },
          {
            label: '启用状态',
            field: 'status',
            popover: 'select',
            popoverOption: {
              select: [
                { label: '开启', value: 1 },
                { label: '关闭', value: 2 }
              ]
            }
          }
        ]
      }
    ]
  }
  return widget
})
const { columns } = useTableColumn()

const { selectedKeys, onSelectChange, createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(params)

const handleBeforeChange = (row: SiteListItem, status: 1 | 2) => {
  return updateApiSiteApi({ id: row.id!, status }).then(() => {
    //ToastUtils.success('操作成功')
    row.status = status
    // run()
  })
}
// 获取解析状态
function getResolveStatus(row: SiteListItem | any) {
  row.resolve_loading = true
  updateApiSiteResolveStatusApi({ id: row.id })
    .then((res) => {
      row.resolve_info.resolve_status = res.resolve_status
    })
    .finally(() => {
      row.resolve_loading = false
    })
}
</script>
